import React, { useState } from 'react';
import './App.css';

const App = () => {
  const [flag, setFlag] = useState(false);
  const [x, setX] = useState(0)
  const [y, setY] = useState(0)
  const [obj, setObj] = useState({
    top: 0,
    left: 0,
    x: 0,
    y: 0
  })
  // 按下
  const onMouseDown = e => {
    // 事件元
    const el = e.target
    el.style.position = 'fixed';
    setObj({
      top: el.offsetTop,
      left: el.offsetLeft,
      x: e.nativeEvent.offsetX,
      y: e.nativeEvent.offsetY
    })
    setFlag(true)
  }
  // 移动
  const onMouseMove = e => {
    if (flag) {
      setX(e.clientX - obj.x)
      setY(e.clientY - obj.y)
    }
  }
  // 抬起
  const onMouseUp = e => {
    console.log(obj)
    setFlag(false)
  }



  return <div
    onMouseMove={onMouseMove}
    onMouseUp={onMouseUp}
    style={{ width: '100vw', height: '100vh' }}
  >
    <button
      style={{ width: 100, height: 100, left: x, top: y }}
      onMouseDown={onMouseDown}

    >拖拽</button>
  </div>
}


export default App